/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import { CloudDbZoneWrapper } from './CloudDBZoneWrapper';
import * as crypto from 'crypto';
import { News } from './News';

export class NewsService {
    async shareIntent() {
        const news =  (await new CloudDbZoneWrapper().queryLatestNews() as Array<News>)[0];

        const now = new Date();
        const oneHourLater = new Date(now.getTime() + 7200000);

        // 统一的格式化函数
        function formatDateWithLocalTimezone(date) {
            const pad = n => String(n).padStart(2, '0');

            const year = date.getFullYear();
            const month = pad(date.getMonth() + 1);
            const day = pad(date.getDate());
            const hours = pad(date.getHours());
            const minutes = pad(date.getMinutes());
            const seconds = pad(date.getSeconds());

            const offset = date.getTimezoneOffset();
            const timezoneSign = offset <= 0 ? '+' : '-';
            const timezoneHours = pad(Math.abs(Math.floor(offset / 60)));
            const timezoneMinutes = pad(Math.abs(offset % 60));
            const timezone = `${timezoneSign}${timezoneHours}:${timezoneMinutes}`;

            return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}${timezone}`;
        }

        const ret1 = formatDateWithLocalTimezone(now);
        const ret2 = formatDateWithLocalTimezone(oneHourLater);

        const intent = {
            intentName: "ViewColumnUpdate",
            intentVersion: "1.0.1",
            identifier: crypto.randomUUID(),
            intentEntityInfo: {
                entityName: "ColumnUpdate",
                entityId: news.newsId.toString(),
                eventImage: "https://gitee.com/gorit/intent-kit-news-demo/blob/main/IntentsKitNewsUpdate/Application/entry/src/main/resources/base/media/sm_img.jpg",
                columnTitle: news.newsType,
                blogTitle: news.title,
                availableBeginTime: ret1,
                availableEndTime: ret2    // one hour later
            }
        }
        // do something here
        return intent;
    }
}
